package com.example.tellwin.mine.act;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.apkfuns.logutils.LogUtils;
import com.example.tellwin.MainApplication;
import com.example.tellwin.R;
import com.example.tellwin.base.CpBaseActivty;
import com.example.tellwin.base.DaggerRxComponent;
import com.example.tellwin.common.Common;
import com.example.tellwin.event.CallEvent;
import com.example.tellwin.event.ExpenseCalendarEvent;
import com.example.tellwin.event.MineEvent;
import com.example.tellwin.event.PayResultEvent;
import com.example.tellwin.mine.bean.AuthResult;
import com.example.tellwin.mine.bean.PayResult;
import com.example.tellwin.mine.bean.WeChatPayBean;
import com.example.tellwin.mine.contract.RechargeContract;
import com.example.tellwin.mine.presenter.RechargePresenter;
import com.example.tellwin.utils.CommonUtils;
import com.example.tellwin.utils.LogUtil;
import com.example.tellwin.utils.ToastUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.http.PATCH;

public class RechargeActivity extends CpBaseActivty implements RechargeContract.View {

    @BindView(R.id.rechrge_et)
    EditText rechrgeEt;
    @BindView(R.id.wechat_rbtn)
    RadioButton wechatRbtn;
    @BindView(R.id.ali_rbtn)
    RadioButton aliRbtn;
    @BindView(R.id.recharge_btn)
    TextView rechargeBtn;

    @Inject
    RechargePresenter mPresenter;
    private IWXAPI api;

    String payId;
    int payType;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    LogUtils.d(payResult);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        LogUtils.d("支付成功");
                        ToastUtil.show(RechargeActivity.this, "充值成功！");
                        finish();
                        EventBus.getDefault().post(new ExpenseCalendarEvent());
                        EventBus.getDefault().post(new MineEvent());
                       // mPresenter.payQuery();
                        // showAlert(PayDemoActivity.this, getString(R.string.pay_success) + payResult);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LogUtils.d("支付失败");
                        //  showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        LogUtils.d("授权成功");
                        //   showAlert(PayDemoActivity.this, getString(R.string.auth_success) + authResult);
                    } else {
                        // 其他状态值则为授权失败
                        LogUtils.d("授权失败");
                        //   showAlert(PayDemoActivity.this, getString(R.string.auth_failed) + authResult);
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        api = WXAPIFactory.createWXAPI(this, Common.WeChatPayId, false);
        api.registerApp(Common.WeChatPayId);
        initViews();
        initEvents();
        initDatas();
    }

    @Override
    protected void initViews() {
        DaggerRxComponent.builder()
                .baseAppComponent(MainApplication.getAppComponent())
                .build()
                .inject(this);
        mPresenter.attachView(this);
    }

    @Override
    protected void initEvents() {
        rechrgeEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().length() > 0) {
                    rechargeBtn.setEnabled(true);
                } else {
                    rechargeBtn.setEnabled(false);
                }

                //这部分是处理如果输入框内小数点后有俩位，那么舍弃最后一位赋值，光标移动到最后
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {

                        rechrgeEt.setText(s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3));

                        rechrgeEt.setSelection(s.toString().trim().length() - 1
                        );
                    }
                }
//这部分是处理如果用户输入以.开头，在前面加上0
                if (s.toString().trim().substring(0).equals(".")) {

                    rechrgeEt.setText("0" + s);
                    rechrgeEt.setSelection(2);
                }
                //这里处理用户 多次输入.的处理 比如输入 1..6的形式，是不可以的
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        rechrgeEt.setText(s.subSequence(0, 1));
                        rechrgeEt.setSelection(1);
                        return;
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        rechargeBtn.setOnClickListener(v -> {
            String text = rechrgeEt.getText().toString();
            if (TextUtils.isEmpty(text)) {
                ToastUtil.show(this, "请输入金额");
                return;
            }
            if (!CommonUtils.isNumeric(text)) {
                ToastUtil.show(this, "请输入正确的金额");
                return;
            }
            double money = Double.valueOf(text);
            if (money < 0.01 || money >= 10000) {
                ToastUtil.show(this, "金额不能小于0.01或大于10000");
                return;
            }
            if (wechatRbtn.isChecked()) {
                payType = 1;
                mPresenter.chargeMoney(rechrgeEt.getText().toString(), 1);
            } else if (aliRbtn.isChecked()) {
                payType = 2;
                mPresenter.chargeMoney(rechrgeEt.getText().toString(), 2);
               // chargeMoneyAli("");
            }
        });
    }

    @Override
    protected void initDatas() {
        setTitle(R.string.recharge);
    }

    @Override
    public void chargeMoneyWeChat(String payId, WeChatPayBean weChatPayBean) {
        this.payId = payId;
        PayReq req = new PayReq();
        req.appId = weChatPayBean.appid;
        req.partnerId = weChatPayBean.partnerid;
        req.prepayId = weChatPayBean.prepayid;
        req.packageValue = "Sign=WXPay";
        req.nonceStr = weChatPayBean.noncestr;
        req.timeStamp = weChatPayBean.timestamp;
        req.sign = weChatPayBean.sign;
        api.sendReq(req);
    }

    @Override
    public void chargeMoneyAli(String data) {

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                //String data = "alipay_sdk=alipay-sdk-java-4.10.209.ALL&app_id=2021002116607548&biz_content=%7B%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22123%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22App%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95Java%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=%E5%95%86%E6%88%B7%E5%A4%96%E7%BD%91%E5%8F%AF%E4%BB%A5%E8%AE%BF%E9%97%AE%E7%9A%84%E5%BC%82%E6%AD%A5%E5%9C%B0%E5%9D%80&sign=RTujL8XHAb%2Bqz4pS3BK7uPuVFh6KrzCZG%2BLud6Ua6Jalz441j9BBd%2F8IBaW%2FE0iMT%2FQQKUXAXTpsDJXwkgOtjYyUrtaQRpDAT1p%2B1ZlS6ep3uP3E5l8X3Za%2Fz5boOfdtwrSQxPm4OkggnPtuHfMLksLIAlJC0Mu0SU1DctrOghHWprcaRf%2ByC7eSi6dUyL1QVbKlpI177feZ0jgIeEt1hpCxkXeTgA6qAgNB5EXfYhQ03IDRjhxTTGYba4pre0ZYD0MaZNdG7v1T5uObNrrTANv7gNZk42vWF4Wd%2FAxPGFCsAbl%2Fk%2BVaRzhj9EYoEXcmNcQ75tIFAdQjTlJTqAoDWw%3D%3D&sign_type=RSA2&timestamp=2020-12-24+19%3A52%3A33&version=1.0";
                PayTask alipay = new PayTask(RechargeActivity.this);
                Map<String, String> result = alipay.payV2(data, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void payQuerySuccess() {
        ToastUtil.show(this, "充值成功！");
        payId = null;
        payType = 0;
        rechrgeEt.setText("");
        finish();
        EventBus.getDefault().post(new ExpenseCalendarEvent());
        EventBus.getDefault().post(new MineEvent());
    }

    @Subscribe
    public void onEvent(PayResultEvent event) {
        if (event.isSuccess) {
            mPresenter.payQuery(payId, payType);
        } else {

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
